
/*
This is for cash slate

*/


var browser=navigator.appName;
if (browser=='Microsoft Internet Explorer'){var IE = true}
else var IE = false

var time = 0;
var timedCount = '';
var online_status = true;  //this tells us if we are on or offline

var current_check = [0.0,[]];
var check_open = false;
var doajax = function(){}  //this is our all purpose ajax function
var db = '' //this is our local db
var local_sync = function(){}  //This will be our syncing function.
  
$(document).ready(function()
{
//Checking offline or online
//goal, wait till we are offline, then check every 5 secs till we are online
    var t;
    timedCount = function(){
        doajax('ping',{},function(){
                $('#new_item,#sync').show();
                $('#status').html('Online')
            });
        if(!online_status){
                $('#status').html('Offline')
                $('#new_item,#sync').hide();    
            }
        
        //confirm('ping')
        time += 5;
        t=setTimeout("timedCount()",5000);
    }
    
    

//GEARS STUFF
    if (!window.google){location.href = "http://gears.google.com/?action=install" +"&message=missinggoogle&return=<your url>";}
      if(!google.gears) {location.href = "http://gears.google.com/?action=install" +"&message=missinggears&return=<your url>";}
     
    db = google.gears.factory.create('beta.database', '1.0');
    db.open('my-database'); 
    
    var gears_i = function(){
            var localServer = google.gears.factory.create('beta.localserver');
            var store = localServer.createManagedStore('test-store');
            store.manifestUrl = 'js/site-manifest.txt';
            store.checkForUpdate();
    }
    
    //gears_i();
    
    var gears_update = function(){
            var localServer = google.gears.factory.create('beta.localserver');
            localServer.removeManagedStore('test-store')
            var store = localServer.createManagedStore('test-store');
            store.manifestUrl = 'js/site-manifest.txt';
            store.checkForUpdate();
    }
    //gears_update();
    

 //TEST STUFF
 $("#header > *").addClass('point');
 //confirm('woot')
 $('#new_item').click(function(){
        dlg_new_item();
    });
  
 $('#open_check0').click(function(){
        current_check = [0.0,[]];
        check_open = true;
        draw_all();
    });
    
  $('#close_check0').click(function(){
        db_add_check(current_check);
        current_check = [0.0,[]];
        check_open = false;
        draw_all();
    });
  
    
    $('#check_db0').click(function(){
        read_db();
        confirm('all done')
    });
    
    $('#sync0').click(function(){
        sync_all();
    });
    
        $('#view').click(function(){
        view_db();
    });

    
var dlg_new_item = function(){
        var dtext = $('<div  title="Adding New Item"><h2>We shall add a new item, this will require an internet connection</h2></div>');
        $('<label>Name</label><br/><input type="text" id="item-name" size="20" ></input><br/>').appendTo(dtext);
        $('<label>Price</label><br/><input type="text" id="item-price" size="20" ></input><br/>').appendTo(dtext);
        dtext.dialog({
            height: 300,width:350,modal: true,overlay: {backgroundColor: '#000',opacity: 0.5},
            buttons: {
                Cancel: function() {$(this).dialog('close');},
                'Add Item': function() {
                    doajax('add_item',{'name':$('#item-name').val(),'price':$('#item-price').val()},function(data){sync_db(data.items);});
                    $(this).dialog('destroy').remove();}
                },
            
            close:function(){$(this).dialog('destroy').remove()}
        });          
    }; 
    
 //AJAX SETUp
    $.ajaxSetup({
       url: "/rpc",
       type: "POST",
       dataType: "json",
       cache: false,
       error: function (XMLHttpRequest, textStatus, errorThrown) {
                  online_status = false;
                  //confirm('Ajax request did not work');
                  }
    });


//AJAX

   doajax = function(action,args,func,cont){
        var cdata = $.toJSON(args)
        $.ajax({data:{action:action,data:cdata},
              success: function(data){
                online_status = true;
                if(data.success == true){
                    if(func){func(data);}
                }
                else{
                    confirm(data.msg);
                    if(func && cont){func(data);}
                }
               }
        });
    }    
 


    

    
//db tools        
    var get_result = function(rs){
        var data = [];
        var count = 0;
        var go = true;
        while (rs.isValidRow()) {
            if(go){
                go=false;
                count = rs.fieldCount();
                var head = [];
                for(var i=0;i<count;i++){
                    head.push(rs.fieldName(i))
                }
                data.push(head);
            }
            var temp = [];
            for(var i=0;i<count;i++){
                temp.push(rs.field(i))
            }
            data.push(temp);
          rs.next();
        }
        rs.close();
        
        return data
    }
    
var stats_dialog = function(tdata){
        var dtext = $('<div class="flora" title="User Stats">Below is the number of pages each of the groups has completed in each section<br/><br/></div>');
        var tab = MakeTable(tdata[0],tdata.slice(1));
        tab.appendTo(dtext);
        dtext.dialog({
            height: 600,width:700,modal: true,overlay: {backgroundColor: '#000',opacity: 0.5},
            buttons: {
                'Cool': function() {$(this).dialog('destroy').remove();}       
            },
            close:function(){$(this).dialog('destroy').remove()}
        });          
    }

 var MakeTable = function(header,data,separator,rowfunc,cellfunc,sfx,sfxstart){
    if(!sfx){sfx='';sfxstart=100;}
    var ndata =  new Array();
    if(separator){
        for(var i=0;i<data.length;i++){
            ndata.push(data[i].split(separator));
        }
    }
    else{ndata = data}
    
    var tab = $('<table class="tablesorter teachertable" border="1" cellpadding="100" cellspacing="1"></table>');
    var head = $('<thead></thead>');
    var hrow = $('<tr></tr>');
    for(var i=0;i<header.length;i++){
        $('<th>'+header[i]+'</th>').appendTo(hrow);    
    }
    hrow.appendTo(head);
    head.appendTo(tab);
    var rows = new Array;
    for(var i=0;i<ndata.length;i++){
        var row = $('<tr id="'+ndata[i][0]+'" id2="'+ndata[i][1]+'"></tr>');
        for(var j=0;j<ndata[i].length;j++){ 
            if(j<sfxstart){var sufx = '';}
            else{var sufx = sfx;}
            var cell = $('<td sname="'+ndata[i][1]+'" tname="'+ndata[i][0]+'" cnum="'+j+'">'+ndata[i][j]+sufx+'</td>');
            cell.appendTo(row);
            cell.click(function(){cellfunc($(this).attr('sname'),$(this).attr('tname'),$(this).attr('cnum'))})
        }
         row.appendTo(tab);
         row.click(function(){rowfunc($(this).attr('id'),$(this).attr('id2'))})
    }
    
    return tab
}

 
    
    var sync_all = function(){

        rs = db.execute('select * from Checks WHERE checkkey is null');
        var new_checks = get_result(rs);
        
        //we want back a list of rows that have [CheckTime ,checkKey]
        if(new_checks.length<=1){confirm('nothing to do this time')}
        else{
            doajax('sync_checks',{'checks':new_checks},function(data){
                //rs = db.execute('DELETE FROM Checks WHERE items is null');
                for(var i=0;i<data.checks.length;i++){ 
                    db.execute('UPDATE Checks SET CheckKey=? WHERE CheckTime=?',data.checks[i]);
                }
                confirm('all done, got back '+data.checks.length)
                draw_all();
            });
        }
        
        
        
        
  //      UPDATE Persons
//SET Address='Nissestien 67', City='Sandnes'
//WHERE LastName='Tjessem' AND FirstName='Jakob'
        
        
        
        
        
        
        //confirm(new_checks)
                
        
    
    }
    
    var view_db = function(){
        rs = db.execute('select * from Checks');
        var new_checks = get_result(rs);
        stats_dialog(new_checks);
    }
    
    
    var get_stuff = function(){
        doajax('get_data',{},function(data){
                
                checks = data.checks;
                draw_all();
                sync_db(data.items);
            })
    
    }
    
    
//DRAW
    var draw_all = function(){
        var items = read_db_items();
        $('#dis_items').html('');  
        for(var i=1;i<items.length;i++){
            $('<div id="'+items[i][0]+'" price="'+items[i][1]+'">--'+items[i]+'</div>').appendTo($('#dis_items')); 
        }   
           
        var checks = read_db_checks();
        $('#dis_checks').html('');  
        for(var i=1;i<checks.length;i++){
            $('<div>--'+checks[i]+'</div>').appendTo($('#dis_checks')); 
        } 
        
         $('#dis_check').html('');  
         if(check_open){
            $('#dis_check').html('Check open, click on an item to add to your cart');
            $('<div>'+current_check+'</div>').appendTo($('#dis_check'));
         }
         else{$('#dis_check').html('No check is currently open');}
         
         if(current_check[0]){$('#check_total').html(current_check[0]); }
         else{$('#check_total').html('0.00'); }
         
         $("#dis_items > *").click(function(){
                var name = $(this).attr('id');
                var price = parseFloat($(this).attr('price'));
                order_item(name,price);
            });
    
    
    }
    
    var order_item = function(name,price){
        current_check[0] += price;
        current_check[1].push(name);
        draw_all();
    }
    
    
    
    //init_tables();
    //get_stuff();
    //timedCount();
    //draw_all();
})
                               
